<script setup>
import { onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { energyType, topologymenu, topologyTree, getContrast } from '@/api/test'

const dataL = ref({
  firstOrder: [],
  secondLevel: [],
  treeVal: []
})

const activeF = ref(0)
const firstClick = (id) => {
  activeF.value = id
  getTopologyTree()
}
const activeS = ref(0)
const secondClick = (id) => {
  activeS.value = id
  getTopologyTree()
}

const treeRef = ref()
/** 树形激活项的ID **/
const treeId = ref(0)
const defaultProps = {
  children: 'children',
  label: 'name'
}
const handleNodeClick = (data) => {
  console.log(data)
  treeId.value = data.id
}
const filterText = ref('')
watch(filterText, (val) => {
  treeRef.value.filter(val)
})
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

// 查询用到的工具函数
const getTodayFormatted = () => {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  const hours = '00'
  const minutes = '00'
  const seconds = '00'
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
/** 查询表单的计算函数 **/
function formatDateToStartOfDay(date) {
  if (typeof date === 'string') {
    date = new Date(date)
    if (isNaN(date.getTime())) {
      throw new Error('Invalid date string')
    }
  }
  if (!(date instanceof Date)) {
    throw new Error('Invalid date')
  }
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day} 00:00:00`
}
function adjustDateByTypeFinal(dateStr, type) {
  const date = new Date(dateStr.replace(' ', 'T'))
  if (isNaN(date.getTime())) throw new Error('Invalid date string')
  if (type === 0) {
    date.setMonth(date.getMonth() - 1)
  } else {
    date.setFullYear(date.getFullYear() - 1)
  }
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} 00:00:00`
}
// 右侧表单
const formInline = ref({
  startTime: '',
  endTime: ''
})
const dateType = ref('daterange')
const typeChart = ref(0)
const changeType = (type) => {
  dateType.value = type
}
const changeTypeChart = (type) => {
  typeChart.value = type
}
const onSubmit = () => {
  console.log('submit!')
}
//echarts图表
const barActive = ref(0)
const barActiveChange = (index) => {
  barActive.value = index
}
const setUpEcharts = () => {
  const chartDom = document.querySelector('.mainE')
  const myChart = echarts.init(chartDom)
  const rawData = [
    [1342.27, 1842.27, 1942.27, 2820.33, 3342.27, 2042.27, 3342.27],
    [3595.66, 1342.27, 1542, 2820.85, 2042.27, 2342.27, 3342.27],
    [2877.94, 3342.27, 1742, 2920.85, 3042.27, 1342.27, 1342.27],
    [1461.66, 2342.27, 1942.99, 1820.85, 3042.27, 6042.27, 3342.27]
  ]
  const grid = {
    left: 100,
    right: 100,
    top: 50,
    bottom: 50
  }
  const series = ['尖', '峰', '平', '谷'].map((name, sid) => {
    return {
      name,
      type: 'bar',
      stack: 'total',
      barWidth: '20%',
      label: {
        show: false,
        formatter: (params) => Math.round(params.value * 1000) / 10 + '%'
      },
      data: rawData[sid].map((d, did) => d)
    }
  })
  const option = {
    //悬停弹窗
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    // 右上角操作按钮
    toolbox: {
      show: true,
      feature: {
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ['line', 'bar'] },
        restore: { show: false },
        saveAsImage: { show: true }
      }
    },
    legend: {},
    grid,
    yAxis: {
      type: 'value',
      min: 0,
      max: 12000
    },
    xAxis: {
      type: 'category',
      data: ['2024-1', '2024-2', '2024-3', '2024-4', '2024-5', '2024-6', '2024-7']
    },
    series
  }
  option && myChart.setOption(option)
}
const pieLEcharts = () => {
  const chartDom = document.querySelector('.mainPL')
  const myChart = echarts.init(chartDom)
  const option = {
    color: [
      '#2ec7c9',
      '#b6a2de',
      '#5ab1ef',
      '#ffb980',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc'
    ],
    title: {
      text: '分时电量',
      left: 'center',
      textStyle: {
        color: '#5ab1ef'
      }
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '8%',
      left: 'center'
    },
    series: [
      {
        name: '分时电量',
        type: 'pie',
        radius: ['20%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside'
        },
        emphasis: {
          label: {
            show: true
          }
        },
        labelLine: {
          show: true
        },
        data: [
          { value: 1048, name: '尖' },
          { value: 735, name: '峰' },
          { value: 580, name: '平' },
          { value: 484, name: '谷' }
        ]
      }
    ]
  }
  option && myChart.setOption(option)
}
const pieREcharts = () => {
  const chartDom = document.querySelector('.mainPR')
  const myChart = echarts.init(chartDom)
  const option = {
    color: [
      '#2ec7c9',
      '#b6a2de',
      '#5ab1ef',
      '#ffb980',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc'
    ],
    title: {
      text: '分时电量',
      left: 'center',
      textStyle: {
        color: '#5ab1ef'
      }
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '8%',
      left: 'center'
    },
    series: [
      {
        name: '分时电量',
        type: 'pie',
        radius: ['20%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside'
        },
        emphasis: {
          label: {
            show: true
          }
        },
        labelLine: {
          show: true
        },
        data: [
          { value: 1048, name: '尖' },
          { value: 735, name: '峰' },
          { value: 580, name: '平' },
          { value: 484, name: '谷' }
        ]
      }
    ]
  }
  option && myChart.setOption(option)
}

// 异步请求
const getTopologyTree = async () => {
  const { code, rows } = await topologyTree({
    energyType: activeF.value,
    topologyId: activeS.value
  })
  if (code !== 200) return
  dataL.value.treeVal = rows
  treeId.value = rows[0].id
  const nowData = getTodayFormatted()
  const sData2 = adjustDateByTypeFinal(nowData, typeChart.value)
  const datas = {
    treeNodeId: rows[0].id,
    beginCollectTime: nowData,
    endCollectTime: nowData,
    type: 'tong',
    name: 'day',
    energyType: 1,
    ont: 'y',
    time: 'time',
    beginCollectTime1: sData2,
    endCollectTime1: sData2
  }
  const data = {
    treeNodeId: '326745fb596d4b82a00434c0bc7b2757',
    beginCollectTime: '2024-02-01 00:00:00',
    endCollectTime: '2024-02-29 24:00:00',
    type: '',
    name: 'day',
    energyType: 1,
    ont: 'y',
    time: 'time',
    beginCollectTime1: '2024-01-01 00:00:00',
    endCollectTime1: '2024-01-31 24:00:00'
  }
}
const getTopologymenu = async () => {
  const { code, rows } = await topologymenu({ menuId: 11 })
  if (code !== 200) return
  dataL.value.secondLevel = rows
  activeS.value = rows[0].topologyId
  getTopologyTree()
}
const getEnergyType = async () => {
  const { code, rows } = await energyType({})
  if (code !== 200) return
  getTopologymenu()
  dataL.value.firstOrder = rows
  activeF.value = rows[0].energyType
}
onMounted(() => {
  pieLEcharts()
  pieREcharts()
  setUpEcharts()
  getEnergyType()
})

// table
const tableData = ref([
  {
    id: 1,
    node: '节点1',
    date: '2023-04-01',
    period: 1234,
    same: 1100,
    onYear: '增长20%'
  },
  {
    id: 2,
    node: '节点2',
    date: '2023-04-02',
    period: 5678,
    same: 5500,
    onYear: '下降10%'
  },
  {
    id: 3,
    node: '节点3',
    date: '2023-04-03',
    period: 3456,
    same: 3300,
    onYear: '增长5%'
  }
  // 根据需要添加更多数据
])
const getSummaries = (param) => {
  const { data } = param
  // 初始化需要计算的列
  const sums = []
  let totalPeriod = 0
  let totalSame = 0

  // 计算本期和同期的总和
  data.forEach((item) => {
    totalPeriod += Number(item.period) || 0
    totalSame += Number(item.same) || 0
  })

  // 计算同比（处理除零异常）
  const calcOnYear = () => {
    if (totalSame === 0) return '-'
    return (((totalPeriod - totalSame) / totalSame) * 100).toFixed(2) + '%'
  }

  // 处理每一列数据
  param.columns.forEach((column, index) => {
    switch (column.property) {
      case 'node':
        sums[index] = '合计'
        break
      case 'date':
        sums[index] = '—' // 特殊符号占位
        break
      case 'period':
        sums[index] = totalPeriod.toLocaleString() // 添加千分位分隔符
        break
      case 'same':
        sums[index] = totalSame.toLocaleString()
        break
      case 'onYear':
        sums[index] = calcOnYear()
        break
      default:
        sums[index] = '—'
    }
  })

  return sums
}
</script>

<template>
  <div class="test">
    <div class="testL">
      <el-scrollbar>
        <!-- 类别 -->
        <div class="LFirst">
          <div class="LFtitle">类别:</div>
          <div class="LFvalue Lvalue">
            <div
              v-for="item in dataL.firstOrder"
              :key="item.energyType"
              class="LFitem Litem"
              :class="{ active: item.energyType === activeF }"
              @click="firstClick(item.energyType)"
            >
              {{ item.energyName }}
            </div>
          </div>
        </div>
        <!-- 标签 -->
        <div class="LFirst">
          <div class="LFtitle">标签:</div>
          <div class="LFvalue Lvalue">
            <div
              v-for="item in dataL.secondLevel"
              :key="item.topologyId"
              class="LFitem Litem"
              :class="{ active: item.topologyId === activeS }"
              @click="secondClick(item.topologyId)"
            >
              {{ item.topologyName }}
            </div>
          </div>
        </div>
        <hr />
        <div class="LTree">
          <div class="Linput">
            <el-input v-model="filterText" style="width: 100%" placeholder="筛选关键字" />
          </div>
          <el-tree
            ref="treeRef"
            :data="dataL.treeVal"
            :props="defaultProps"
            @node-click="handleNodeClick"
            default-expand-all
            :highlight-current="true"
            :filter-node-method="filterNode"
          />
        </div>
      </el-scrollbar>
    </div>
    <div class="testR">
      <el-scrollbar height="100vh">
        <div class="rTop">
          <div class="rForm">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="时间范围" style="width: 40%">
                <el-date-picker
                  v-model="formInline.startTime"
                  :type="dateType"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="rCenter">
          <div class="rCenterTop">
            <div class="rTopTitle">分时电量</div>
            <div class="pieT">
              <div class="mainPL"></div>
              <div class="mainPR"></div>
            </div>
          </div>
          <div class="barB">
            <div class="barBTop">
              <div class="mainBT">
                <div
                  class="mainBTB"
                  :class="{ mainBTBAc: barActive === 0 }"
                  @click="barActiveChange(0)"
                >
                  电量
                </div>
                <div
                  class="mainBTB"
                  :class="{ mainBTBAc: barActive === 1 }"
                  @click="barActiveChange(1)"
                >
                  电费
                </div>
                <div class="mainBTBK"></div>
              </div>
              <div class="mainE"></div>
            </div>
          </div>
        </div>
        <div class="rBottom">
          <div class="rTable">
            <el-table
              :data="tableData"
              :summary-method="getSummaries"
              show-summary
              border
              style="width: 100%"
            >
              <el-table-column prop="node" label="节点" width="180" />
              <el-table-column prop="date" label="时间" width="180" />
              <el-table-column prop="period" label="本期" />
              <el-table-column prop="same" label="同期" />
              <el-table-column prop="onYear" label="同比" />
            </el-table>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<style scoped lang="scss">
div {
  box-sizing: border-box;
}
.test {
  display: flex;
  justify-content: space-between;
  width: 100vw;
  height: 100vh;
  background: #efefef;
  .testL {
    padding: 20px;
    width: 17%;
    height: 100%;
    font-size: 14px;
    background: #fff;
    .LFirst {
      display: flex;
      .LFtitle {
        width: 55px;
      }
      .LFvalue {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        .LFitem {
          margin: 0 10px;
          margin-bottom: 10px;
          padding: 3px 15px;
          border-radius: 5px;
          background: #d7d7d7;
          cursor: pointer;
        }
        .active {
          background: #6699ff;
        }
      }
    }
    .Linput {
      margin-top: 10px;
      margin-bottom: 10px;
      width: 100%;
    }
  }
  .testR {
    padding: 20px;
    width: 82.5%;
    height: 100%;
    background: #fff;
    .rTop {
      width: 100%;
      height: 10%;
      .tabT {
        display: flex;
        justify-content: space-around;
        width: 100%;
        .tadTc {
          width: 30%;
          text-align: center;
          border-radius: 5px;
          background: #dcdfe6;
          cursor: pointer;
        }
        .tadTcT {
          width: 35%;
          text-align: center;
          border-radius: 5px;
          background: #dcdfe6;
          cursor: pointer;
        }
        .activeT {
          background: #1890ff;
          color: #fff;
        }
      }
    }
    .rCenter {
      width: 100%;
      height: 90vh;
      .rCenterTop {
        height: 50%;
        border: 1px solid #dcdfe6;
        .rTopTitle {
          padding-left: 20px;
          width: 100%;
          height: 10%;
          line-height: 35px;
          font-weight: 700;
          border-bottom: 1px solid #dcdfe6;
        }
        .pieT {
          display: flex;
          width: 100%;
          height: 90%;
          .mainPL {
            width: 50%;
          }
          .mainPR {
            width: 50%;
          }
        }
      }
      .barB {
        margin-top: 20px;
        height: 50%;
        border: 1px solid #ced1d6;
        .barBTop {
          height: 100%;
          .mainBT {
            display: flex;
            height: 10%;
            background: #f5f7fa;

            .mainBTB {
              width: 5%;
              text-align: center;
              font-size: 14px;
              line-height: 35px;
              border-right: 1px solid #ced1d6;
              border-bottom: 1px solid #ced1d6;
              cursor: pointer;
            }
            .mainBTBK {
              flex: 1;
              border-bottom: 1px solid #ced1d6;
            }
            .mainBTBAc {
              background: #fff;
              color: #1890ff;
              border-bottom: 1px solid #fff;
            }
          }
          .mainE {
            height: 90%;
          }
        }
      }
    }
    .rBottom {
      padding-top: 40px;
      width: 100%;
      height: 40vh;
    }
  }
}
.el-tree {
  background-color: transparent;
}
</style>
